import 'package:awak/common/utils/util_text.dart';
import 'package:awak/common/utils/util_dialog.dart';
import 'package:awak/bloc/auth/auth_bloc.dart';
import 'package:awak/bloc/auth/auth_event.dart';
import 'package:awak/bloc/auth/auth_state.dart';
import 'package:awak/common/models/plan.dart';
import 'package:awak/common/utils/util_toast.dart';
import 'package:awak/common/values/svg.dart';
import 'package:beamer/beamer.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:async';
import 'dart:convert';

class AddPlanPage extends StatefulWidget {
  const AddPlanPage({super.key});

  @override
  State<AddPlanPage> createState() => _AddPlanPageState();
}

class _AddPlanPageState extends State<AddPlanPage> {
  DateTime? _startTime;
  DateTime? _endTime;
  AssetEntity? _selectedImage;
  final TextEditingController _titleController = TextEditingController();
  final TextEditingController _descriptionController = TextEditingController();
  String _durationText = '00:00';
  Timer? _autoSaveTimer;

  @override
  void initState() {
    super.initState();
    _loadDraftData();

    // 添加文本输入监听器，实现自动保存
    _titleController.addListener(_onTextChanged);
    _descriptionController.addListener(_onTextChanged);
  }

  @override
  void dispose() {
    _autoSaveTimer?.cancel();
    _titleController.removeListener(_onTextChanged);
    _descriptionController.removeListener(_onTextChanged);
    _titleController.dispose();
    _descriptionController.dispose();
    super.dispose();
  }

  void _onTextChanged() {
    // 取消之前的定时器
    _autoSaveTimer?.cancel();

    // 设置新的定时器，2秒后自动保存
    _autoSaveTimer = Timer(Duration(seconds: 2), () {
      if (mounted && _hasContent()) {
        _saveDraftDataSilently();
      }
    });
  }

  void _updateDuration() {
    if (_startTime == null || _endTime == null) {
      setState(() {
        _durationText = '00:00';
      });
      return;
    }

    final difference = _endTime!.difference(_startTime!);

    if (difference.isNegative) {
      setState(() {
        _durationText = '00:00';
      });
      return;
    }

    final days = difference.inDays;
    final hours = difference.inHours % 24;
    final minutes = difference.inMinutes % 60;

    setState(() {
      if (days > 0) {
        _durationText = '${days}d ${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}';
      } else {
        _durationText = '${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}';
      }
    });
  }

  Future<void> _loadDraftData() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final draftData = prefs.getString('plan_draft');

      if (draftData != null) {
        final data = json.decode(draftData) as Map<String, dynamic>;

        setState(() {
          // 加载时间数据
          if (data['startTime'] != null) {
            _startTime = DateTime.fromMillisecondsSinceEpoch(data['startTime']);
          }
          if (data['endTime'] != null) {
            _endTime = DateTime.fromMillisecondsSinceEpoch(data['endTime']);
          }

          // 加载文本数据
          _titleController.text = data['title'] ?? '';
          _descriptionController.text = data['description'] ?? '';

        });

        // 更新时长显示
        _updateDuration();
      }
    } catch (e) {
      print('Error loading draft data: $e');
    }
  }

  Future<void> _saveDraftData() async {
    try {
      final prefs = await SharedPreferences.getInstance();

      final data = {
        'startTime': _startTime?.millisecondsSinceEpoch,
        'endTime': _endTime?.millisecondsSinceEpoch,
        'title': _titleController.text,
        'description': _descriptionController.text,
        'savedAt': DateTime.now().millisecondsSinceEpoch,
      };

      await prefs.setString('plan_draft', json.encode(data));

      if (mounted) {
        AwakToast.showCustomToast(context, 'Draft saved successfully');
      }
    } catch (e) {
      print('Error saving draft data: $e');
      if (mounted) {
        AwakToast.showCustomToast(context, 'Failed to save draft');
      }
    }
  }

  Future<void> _saveDraftDataSilently() async {
    try {
      final prefs = await SharedPreferences.getInstance();

      final data = {
        'startTime': _startTime?.millisecondsSinceEpoch,
        'endTime': _endTime?.millisecondsSinceEpoch,
        'title': _titleController.text,
        'description': _descriptionController.text,
        'savedAt': DateTime.now().millisecondsSinceEpoch,
      };

      await prefs.setString('plan_draft', json.encode(data));
    } catch (e) {
      print('Error saving draft data silently: $e');
    }
  }

  Future<void> _clearDraftData() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.remove('plan_draft');
    } catch (e) {
      print('Error clearing draft data: $e');
    }
  }

  Future<bool> _hasDraftData() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      return prefs.containsKey('plan_draft');
    } catch (e) {
      return false;
    }
  }

  @override
  Widget build(BuildContext context) {
    return BlocListener<AwakBloc, AwakState>(
      listener: (context, state) {
        if (state is PlanCreated) {
          _clearDraftData();
          Beamer.of(context).beamBack();
        } else if (state is PlanFailure) {
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(SnackBar(content: Text(state.message)));
        }
      },
      child: Scaffold(
        body: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [Color(0xFFD7F349), Color(0xFFFFFABA)],
            ),
          ),
          child: Scaffold(
            backgroundColor: Colors.transparent,
            appBar: AppBar(
              backgroundColor: Colors.transparent,
              elevation: 0,
              leading: IconButton(
                icon: Icon(AwakSvg.back, color: Colors.black),
                onPressed: () => Beamer.of(context).beamBack(),
              ),
              title: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text('ADD PLAN', style: AwakText.titleStyle),
                  SizedBox(width: 8.w),
                  FutureBuilder<bool>(
                    future: _hasDraftData(),
                    builder: (context, snapshot) {
                      if (snapshot.data == true) {
                        return Container(
                          padding: EdgeInsets.symmetric(horizontal: 6.w, vertical: 2.h),
                          decoration: BoxDecoration(
                            color: Colors.orange,
                            borderRadius: BorderRadius.circular(8.r),
                          ),
                          child: Text(
                            'Draft',
                            style: AwakText.body14Style.copyWith(
                              fontSize: 10.sp,
                              color: Colors.white,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        );
                      }
                      return SizedBox.shrink();
                    },
                  ),
                ],
              ),
              centerTitle: true,
              actions: [
                Padding(
                  padding: EdgeInsets.only(right: 16.w),
                  child: Icon(AwakSvg.plan, size: 24.w, color: Colors.black),
                ),
              ],
            ),
            body: SingleChildScrollView(
              padding: EdgeInsets.all(16.w),
              child: Column(
                children: [
                  _buildTimeSelector(
                    icon: Icons.access_time,
                    title: 'START TIME',
                    selectedTime: _startTime,
                    onTap: () => _selectDateTime(true),
                  ),
                  SizedBox(height: 16.h),
                  _buildEndTimeWithCountdown(),
                  SizedBox(height: 16.h),
                  _buildImageSelector(),
                  SizedBox(height: 16.h),
                  _buildTextInput(
                    controller: _titleController,
                    title: 'Plan Title',
                    hint: 'please enter Your plan title',
                    maxLines: 2,
                  ),
                  SizedBox(height: 16.h),
                  _buildTextInput(
                    controller: _descriptionController,
                    title: 'Description Of The Plan',
                    hint: 'please enter Your Description Of The Plan',
                    maxLines: 4,
                  ),
                  SizedBox(height: 40.h),
                  _buildActionButtons(),
                  SizedBox(height: 40.h),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildTimeSelector({
    required IconData icon,
    required String title,
    required DateTime? selectedTime,
    required VoidCallback onTap,
  }) {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(icon, size: 20.w, color: Colors.black),
              SizedBox(width: 8.w),
              Text(
                title,
                style: AwakText.body14Style.copyWith(
                  fontWeight: FontWeight.w600,
                  color: Colors.black,
                ),
              ),
            ],
          ),
          SizedBox(height: 12.h),
          GestureDetector(
            onTap: onTap,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Text(
                  selectedTime != null
                      ? '${selectedTime.year}-${selectedTime.month.toString().padLeft(2, '0')}-${selectedTime.day.toString().padLeft(2, '0')} ${selectedTime.hour.toString().padLeft(2, '0')}:${selectedTime.minute.toString().padLeft(2, '0')}'
                      : 'Please Select',
                  style: AwakText.body14Style.copyWith(
                    color: selectedTime != null ? Colors.black : Colors.grey,
                    fontWeight: FontWeight.w400,
                  ),
                ),
                SizedBox(width: 8.w),
                Icon(
                  Icons.keyboard_arrow_down,
                  color: Colors.grey,
                  size: 20.w,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildEndTimeWithCountdown() {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Icon(Icons.access_time, size: 20.w, color: Colors.black),
                  SizedBox(width: 8.w),
                  Text(
                    'END TIME',
                    style: AwakText.body14Style.copyWith(
                      fontWeight: FontWeight.w600,
                      color: Colors.black,
                    ),
                  ),
                ],
              ),
              SizedBox(height: 12.h),
              GestureDetector(
                onTap: () => _selectDateTime(false),
                child: Row(
                  children: [
                    Text(
                      _endTime != null
                          ? '${_endTime!.year}-${_endTime!.month.toString().padLeft(2, '0')}-${_endTime!.day.toString().padLeft(2, '0')} ${_endTime!.hour.toString().padLeft(2, '0')}:${_endTime!.minute.toString().padLeft(2, '0')}'
                          : 'Please Select',
                      style: AwakText.body14Style.copyWith(
                        color: _endTime != null ? Colors.black : Colors.grey,
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                    SizedBox(width: 8.w),
                    Icon(
                      Icons.keyboard_arrow_down,
                      color: Colors.grey,
                      size: 20.w,
                    ),
                  ],
                ),
              ),
            ],
          ),
          Spacer(),
          Container(
            padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 16.h),
            decoration: BoxDecoration(
              color: const Color(0xFFD8F34A),
              borderRadius: BorderRadius.circular(8.r),
            ),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text(
                  'Count Down',
                  style: AwakText.body14Style.copyWith(
                    fontWeight: FontWeight.w600,
                    color: Colors.black,
                    fontSize: 12.sp,
                  ),
                ),
                SizedBox(width: 10.w),
                Text(
                  _durationText,
                  style: AwakText.body14Style.copyWith(
                    fontWeight: FontWeight.w500,
                    color: Colors.black,
                    fontSize: 12.sp,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildImageSelector() {
    return Container(
      width: double.infinity,
      height: 150.h,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: _selectedImage != null
          ? ClipRRect(
              borderRadius: BorderRadius.circular(11.r),
              child: AssetEntityImage(
                _selectedImage!,
                fit: BoxFit.cover,
                width: double.infinity,
                height: 120.h,
              ),
            )
          : GestureDetector(
              onTap: _selectImage,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    Icons.add_photo_alternate_outlined,
                    size: 40.w,
                    color: Colors.grey,
                  ),
                  SizedBox(height: 8.h),
                  Text(
                    'Select Plan Image',
                    style: AwakText.body14Style.copyWith(
                      color: Colors.grey,
                      fontWeight: FontWeight.w400,
                    ),
                  ),
                ],
              ),
            ),
    );
  }

  Widget _buildTextInput({
    required TextEditingController controller,
    required String title,
    required String hint,
    int maxLines = 1,
  }) {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            title,
            style: AwakText.body14Style.copyWith(
              fontWeight: FontWeight.w600,
              color: Colors.black,
            ),
          ),
          SizedBox(height: 10.h),
          TextField(
            controller: controller,
            maxLines: maxLines,
            decoration: InputDecoration(
              hintText: hint,
              hintStyle: AwakText.body14Style.copyWith(
                color: Colors.grey,
                fontWeight: FontWeight.w400,
              ),
              border: InputBorder.none,
              contentPadding: EdgeInsets.zero,
            ),
            style: AwakText.body14Style.copyWith(
              color: Colors.black,
              fontWeight: FontWeight.w400,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildActionButtons() {
    return Row(
      children: [
        Expanded(
          child: GestureDetector(
            onTap: _showSaveAsDraftDialog,
            child: Container(
              height: 50.h,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12.r),
                border: Border.all(color: Colors.black, width: 1.w),
              ),
              child: Center(
                child: Text(
                  'Save As Draft',
                  style: AwakText.body14Style.copyWith(
                    fontWeight: FontWeight.w600,
                    color: Colors.black,
                  ),
                ),
              ),
            ),
          ),
        ),
        SizedBox(width: 16.w),
        Expanded(
          child: GestureDetector(
            onTap: _createPlan,
            child: Container(
              height: 50.h,
              decoration: BoxDecoration(
                color: const Color(0xFFB6F558),
                borderRadius: BorderRadius.circular(12.r),
                border: Border.all(color: Colors.black, width: 1.w),
              ),
              child: Center(
                child: Text(
                  'Create',
                  style: AwakText.body14Style.copyWith(
                    fontWeight: FontWeight.w600,
                    color: Colors.black,
                  ),
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  Future<void> _selectDateTime(bool isStartTime) async {
    final now = DateTime.now();
    DateTime initialDate = now;

    if (isStartTime && _startTime != null && _startTime!.isAfter(now)) {
      initialDate = _startTime!;
    } else if (!isStartTime && _endTime != null && _endTime!.isAfter(now)) {
      initialDate = _endTime!;
    }

    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.white,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20.r)),
      ),
      builder: (BuildContext context) {
        DateTime tempDateTime = initialDate;
        return Container(
          height: 350.h,
          child: Column(
            children: [
              Container(
                padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    TextButton(
                      onPressed: () => Navigator.of(context).pop(),
                      child: Text(
                        'Cancel',
                        style: AwakText.body14Style.copyWith(
                          color: Colors.grey,
                        ),
                      ),
                    ),
                    Text(
                      isStartTime ? 'Select Start Time' : 'Select End Time',
                      style: AwakText.body16Style.copyWith(
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    TextButton(
                      onPressed: () {
                        setState(() {
                          if (isStartTime) {
                            _startTime = tempDateTime;
                          } else {
                            _endTime = tempDateTime;
                          }
                        });
                        _updateDuration();
                        _onTextChanged(); // 触发自动保存
                        Navigator.of(context).pop();
                      },
                      child: Text(
                        'Confirm',
                        style: AwakText.body14Style.copyWith(
                          color: Colors.black,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              Divider(height: 1.h, color: Colors.grey[300]),
              Expanded(
                child: CupertinoDatePicker(
                  mode: CupertinoDatePickerMode.dateAndTime,
                  initialDateTime: initialDate,
                  minimumDate: now,
                  maximumDate: now.add(Duration(days: 365)),
                  onDateTimeChanged: (DateTime newDateTime) {
                    tempDateTime = newDateTime;
                  },
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Future<void> _selectImage() async {
    final List<AssetEntity>? result = await AssetPicker.pickAssets(
      context,
      pickerConfig: AssetPickerConfig(
        maxAssets: 1,
        requestType: RequestType.image,
        themeColor: Color(0xFFD7F349),
      ),
    );

    if (result != null && result.isNotEmpty) {
      setState(() {
        _selectedImage = result.first;
      });
      _onTextChanged();
    }
  }

  void _showSaveAsDraftDialog() {
    if (_hasContent()) {
      showAwakDialog(
        context: context,
        title: 'Kindly Reminder',
        description: 'Need me to save the completed content?',
        onCancel: () {
          Beamer.of(context).beamBack();
        },
        onConfirm: () async {
          await _saveDraftData();
          if (mounted) {
            Beamer.of(context).beamBack();
          }
        },
      );
    } else {
      Beamer.of(context).beamBack();
    }
  }

  bool _hasContent() {
    return _startTime != null ||
        _endTime != null ||
        _selectedImage != null ||
        _titleController.text.isNotEmpty ||
        _descriptionController.text.isNotEmpty;
  }

  void _createPlan() {
    if (_validateInput()) {
      final currentUser = context.read<AwakBloc>().userRepository.currentUser;
      if (currentUser != null) {
        final plan = Plan(
          title: _titleController.text,
          description: _descriptionController.text,
          picture: _selectedImage != null ? 'custom_image' : 'plan1',
          startTime: _startTime ?? DateTime.now(),
          endTime: _endTime ?? DateTime.now().add(Duration(hours: 1)),
          state: 'not_started',
          userId: currentUser.id!,
        );

        context.read<AwakBloc>().add(CreatePlanEvent(plan));
      }
    }
  }

  bool _validateInput() {
    if (_titleController.text.isEmpty) {
      AwakToast.showCustomToast(context, 'Please enter plan title');
      return false;
    }

    if (_descriptionController.text.isEmpty) {
      AwakToast.showCustomToast(context, 'Please enter description of the plan');
      return false;
    }

    if (_selectedImage == null) {
      AwakToast.showCustomToast(context, 'Please select plan image');
      return false;
    }

    if (_startTime == null || _endTime == null) {
      AwakToast.showCustomToast(context, 'Please select start and end time');
      return false;
    }

    if (_endTime!.isBefore(_startTime!)) {
      AwakToast.showCustomToast(context, 'End time must be after start time');
      return false;
    }

    return true;
  }
}
